package com.yufei.infoExtractor.util;

import java.io.File;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathUtil {
public static String getNodeTextByXPath(String source,String xpath) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{
	String value=null;
	 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	    domFactory.setNamespaceAware(true); // never forget this!


	    DocumentBuilder builder = domFactory.newDocumentBuilder();
	    Document doc = builder.parse(source);

	    XPathFactory factory = XPathFactory.newInstance();
	    XPath path = factory.newXPath();
	    XPathExpression expr 
	     = path.compile(xpath);
	   
	    Object result = expr.evaluate(doc, XPathConstants.NODESET);
	    NodeList nodes = (NodeList) result;
	    if(nodes==null||nodes.getLength()==0){
	    	return null;
	    }
	    value=nodes.item(0).getTextContent();
	return value;
}
public static void main(String[] args) throws IOException, XPathExpressionException, ParserConfigurationException, SAXException{
	String html=CommonUtil.getHtmlContent(null, false, "http://www.dianping.com/shop/5295184");
	//String html=CommonUtil.getStringFromFile(new File(
		//	"src/test/resources/html/links.html"));
	html=HtmlUtil.removeJSAndCss(html);
	/*String value=XPathUtil.getNodeTextByXPath("links.html","//div[@class=\"comment-rst\"]/span[@itemprop=\"count\"]/text()");
	*/
	System.out.print(html);
}
}
